package com.jse.json;

import java.util.Collection;
import java.util.List;
import java.util.Map;

public class Json {

	public static Object parse(String s) {
		if(s==null)return null;
		else if(s.charAt(0)=='{')return new JsonObject(s);
		else if(s.charAt(0)=='[')return new JsonArray(s);
		else if(s.charAt(0)=='<')return XML.toJSONObject(s);
		return s;
	}
	
	public static <T>T json(Object o) {//转化为jsonobject或jsonarray
		if(o instanceof Collection c)return (T)jsonArray(c);
		if(o instanceof Map c) {
			if(c.getClass().getName().endsWith(".ScriptObjectMirror")) {
    			if(c.toString().equals("[object Array]"))return (T)new JsonArray(c.values());
    		}
			return (T)jsonObject(c);
		}
		if(o instanceof String s)return (T)parse(s);
		return null;
	}

	public static JsonObject jsonObject(Object m) {
		if(m instanceof JsonObject j)return j;
		if(m instanceof Map j)return new JsonObject(j);
		if(m instanceof String s)return new JsonObject(s);
		return new JsonObject(m);
	}
	public static JsonArray jsonArray(Object m) {
		if(m instanceof JsonArray j)return j;
		if(m instanceof Collection c)return new JsonArray(c);
		if(m instanceof Map j)return new JsonArray(j);
		if(m instanceof String s)return new JsonArray(s);
		return new JsonArray(m);
	}

	public static String toJson(Object obj) {
		if(obj==null) {
    		return null;
    	}else if(obj instanceof JsonArray j) {
    		return j.toString();
    	}else if(obj instanceof JsonObject j) {
    		return j.toString();
    	}else if(obj instanceof String s) {
    		return s;
    	}else if(obj.getClass().isArray()) {
    		return new JsonArray(obj).toString();
    	}else if(obj instanceof Collection<?> c) {
    		return new JsonArray((Collection<?>)c).toString();
    	}else if(obj instanceof Map<?,?> j) {
    		if(j.getClass().getName().endsWith(".ScriptObjectMirror")) {
    			if(j.toString().equals("[object Array]"))return new JsonArray(j.values()).toString();
    		}
    		return new JsonObject((Map<?,?>)j).toString();
    	}else if(obj.getClass().getName().startsWith("java.lang.")) {
    		return obj.toString();
    	}else {
    		return new JsonObject(obj).toString();
    	}
	}

	public static <T> T parse(String json,Class<T> c) {
		var o=parse(json);
		if(c.isInstance(o))return(T)o;
		if(o instanceof JsonObject j)return j.toBean(c);
		throw new RuntimeException("not cast class:"+c);
	}

	public static void main(String[] args) {
		JsonObject jo=new JsonObject(Map.of("a",222,"v","xx"));
//		jo.put("a", 123);
//		jo.put("v", "xxx");
		System.out.println(jo);
	}
}
